﻿using EFCoreIdentitySample.Repository.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace EFCoreIdentitySample.Repository
{
    public static class WebHostMigrationExtension
    {

        public static IWebHost MigrateDbContext<TContext>(this IWebHost webHost, Action<TContext, IServiceProvider> act)
            where TContext : DbContext
        {
            using (var scope = webHost.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var logger = services.GetRequiredService<ILogger<TContext>>();
                var ctx= services.GetRequiredService<TContext>();
                try
                {
                    ctx.Database.Migrate();
                    act.Invoke(ctx, services);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex,"初始化种子数据失败!");
                }
            }
            return webHost;
        }
    }
}
